package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关过滤器,该过滤器实现鉴权,
 * 1.对用户的访问进行鉴权,如果是登录,则直接放行
 * 2.如果不是登录,则判断是否有jwt令牌,如果没有则拒绝访问
 * 3.如果携带令牌,则需要对令牌进行校验,如果校验成功,则放行,如果校验失败,则拒绝访问,放置修改jwt的载荷内容从而通过鉴权去访问问服务
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.根据请求对象来获取请求的URI,来判断是否为登录请求
        boolean result = request.getURI().getPath().contains("/admin/login");
        if (result) {
            return chain.filter(exchange);
        }
        //4.如果不是请求信息,则需要获取请求头
        HttpHeaders headers = request.getHeaders();
        //5.获取请求头中的token,并对token进行非空判断,如果为空,则拒绝访问,并完成响应
        String token = headers.getFirst("token");
        if (StringUtils.isEmpty(token)) {
            //响应中放入响应码,没有访问权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
        //6.对token进行校验
        //6.1校验不成功,则拒绝访问
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
